<template>
  <div>
    <Modal
      v-model="showCreateUserModal"
      title="添加用户"
      :mask-closable="false"
      :closable="false"
    >
      <Form
        label-position="right"
        :label-width="100"
        ref="userForm"
        :model="userForm"
        :rules="userValidate"
      >
        <FormItem label="用户名" prop="username">
          <Input
            clearable
            placeholder="请输入用户名"
            v-model="userForm.username"
          />
        </FormItem>
        <FormItem label="真实姓名" prop="real_name">
          <Input
            clearable
            placeholder="请输入真实姓名"
            v-model="userForm.real_name"
          />
        </FormItem>
        <FormItem label="密码" prop="password">
          <Input
            placeholder="请输入密码"
            type="password"
            password
            v-model="userForm.password"
          />
        </FormItem>
        <FormItem label="性别" prop="gender">
          <RadioGroup v-model="userForm.gender">
            <Radio label="male">男</Radio>
            <Radio label="female" style="margin-left: 20px">女</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="联系电话" prop="phone">
          <Input
            clearable
            placeholder="请输入联系电话"
            v-model="userForm.phone"
          />
        </FormItem>
        <FormItem label="电子邮箱" prop="email">
          <Input
            clearable
            placeholder="请输入电子邮箱"
            v-model="userForm.email"
          />
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input v-model="userForm.remark" type="textarea" :rows="5" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleCreateUserCancel">取消</Button>
        <Button type="primary" @click="handleCreateUserSubmit('userForm')"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import { createUser } from "@/api/HttpAutoTestService/user";

export default {
  name: "user-create",
  components: {},
  props: {
    createUser: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    showCreateUserModal: {
      get() {
        return this.createUser;
      },
      set(val) {
        this.$emit("update:createUser", val);
      },
    },
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!/^[A-Za-z]+\w*[A-Za-z0-9]$/.test(value)) {
        callback(
          new Error(
            "只能由字母、数字、下划线组成；并以字母开头，字母、数字结尾"
          )
        );
      }
      callback();
    };
    const validatePhone = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号"));
      }
      callback();
    };
    return {
      userForm: {
        username: "",
        real_name: "",
        password: "123456",
        gender: "male",
        phone: "",
        email: "",
        remark: "",
      },
      userValidate: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { validator: validateUsername, trigger: "blur" },
        ],
        real_name: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" },
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" },
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          {
            type: "string",
            min: 11,
            max: 11,
            message: "请输入11位手机号",
            trigger: "blur",
          },
          { validator: validatePhone, trigger: "blur" },
        ],
        email: [
          { required: true, message: "电子邮箱不能为空", trigger: "blur" },
          { type: "email", message: "电子邮箱格式不正确", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleCreateUserSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          createUser(this.userForm)
            .then((res) => {
              if (res.status === 201) {
                this.$Message.info("创建成功");
                this.handleCreateUserCancel();
                this.$emit("initUserTable");
              } else {
                this.$Message.error("创建失败");
              }
            })
            .catch((err) => {
              this.$Modal.error({
                title: "系统异常，请联系管理员……",
                content: JSON.stringify(err),
                closable: true,
              });
            });
        }
      });
    },

    handleCreateUserCancel() {
      this.userForm = {
        username: "",
        real_name: "",
        password: "123456",
        gender: "male",
        phone: "",
        email: "",
        remark: "",
      };
      this.showCreateUserModal = false;
      this.$refs["userForm"].resetFields();
    },
  },
};
</script>

<style scoped>
</style>
